// pages/myAccount/myAccount.js
import request from "../../utils/request";
import {
	shareOptions
} from "../../utils/access";
const api = require("../../config/api");
import { jump } from "../../utils/utils";

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		// 可用余额
		cashBalance: 0,
		// 提现余额
		balance: null,
	},
	// 获取可用余额
	async getCashBalance() {
		const res = await request.get(api.cashBalance)
		this.setData({
			cashBalance: res?.data
		})
		wx.stopPullDownRefresh()
	},
	// 全部提现按钮
	cashClick() {
		let that = this;
		if (that.data.cashBalance >= 1) {
			this.secondModal.show();
		} else {
			wx.showToast({
				title: '最低提现1元',
				icon: "none",
				duration: 2000,
			});
		}
	},
	// 跳转余额明细
	toDetail(){
		jump('balanceDetail')
	},
	// 金额改变
	balanceInput(e) {
		const value = e.detail.value
		const [priceStart, priceEnd] = value?.split('.')
		let prcie = value
		// 禁止输入第三位小数
		if (priceEnd?.length > 2) {
			prcie = `${priceStart}.${priceEnd.slice(0, 2)}`
		}
		// 判断开头是否有小数点
		if (prcie.indexOf('.') === 0) {
			prcie = prcie.replace('.', '')
		}
		this.setData({
			balance: prcie,
		})
	},
	// 确认提现
	async confirm(e) {
		const {
			balance,
			cashBalance
		} = this.data
		if (+balance < 1) {
			wx.showToast({
				title: '最低提现1元',
				icon: "none",
				duration: 2000,
			})
			return
		}
		if (+balance > +cashBalance) {
			wx.showToast({
				title: `最多提现${cashBalance}元`,
				icon: "none",
				duration: 2000,
			})
			return
		}
		if (+balance > 10000) {
			wx.showToast({
				title: '最高提现10000元',
				icon: "none",
				duration: 2000,
			})
			return
		}
		if (this.loading) return
		this.loading = true
		this.modal.hide()
		const res = await request.post(api.getCash, {
			cashAmount: balance,
			drawType: 20,
		});
		if (res.httpStatus == 200) {
			wx.showToast({
				title: '提现申请成功',
				icon: "none",
			});
			this.setData({
				balance: null
			})
			this.modal.hide();
			this.loading = false
			setTimeout(() => {
				wx.navigateBack({
					delta: 1,
				});
			}, 500);
		}
		this.loading = false

	},
	// 弹窗关闭
	close() {
		this.modal.hide();
		this.setData({
			balance: null
		})
	},
	// 二次确认
	secondConfirm(){
		this.secondModal.hide()
		this.modal.show();
	},
	// 二次关闭
	secondClose() {
		this.secondModal.hide()
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		this.getCashBalance()
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
		this.modal = this.selectComponent('#modal')
		this.secondModal = this.selectComponent('#secondModal')
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {
		this.getCashBalance()
	},

	// 用户点击右上角分享
	onShareAppMessage(e) {
		return shareOptions('default', e)
	},
})